import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';
import 'package:hitutor/Widget/WordsPlayer.dart';

import 'WordsTestDone.dart';

class WordsTest extends StatefulWidget {
  static int NoAnswer = 0;
  static int AnswerRight = 1;
  static int AnswerError = 2;
  static int vocabularyQuizId = 0;
  static int sec = 0;

  dynamic data;

  WordsTest(this.data) {
    vocabularyQuizId = data["vocabularyQuizId"];
  }

  @override
  State<StatefulWidget> createState() {
    return _WordsTest();
  }
}

class _WordsTest extends State<WordsTest> {
  List<dynamic> questions = [];
  int currentPos = 0;

  nextClick(int state) {
    if (state != WordsTest.AnswerRight) {
      questions.add(questions[currentPos]);
    }
    if (currentPos == questions.length - 1) {
      PageUtil().openReplace(context, WordsTestDone());
      return;
    }
    currentPos += 1;
    setState(() {});
    WordsTest.sec = 0;
  }

  late Timer _timer;

  @override
  void initState() {
    questions = widget.data["questions"];
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        WordsTest.sec += 1;
        print("sec:${WordsTest.sec}");
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    if (_timer.isActive) {
      _timer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double progress = (currentPos + 1) / questions.length;
    print("$currentPos / ${questions.length}");
    return MyPage(
        "字彙測驗",
        Column(children: [
          Expanded(
              child: questions[currentPos]["questionType"] == "Cloze"
                  ? WordsTestImage(questions[currentPos], nextClick: nextClick)
                  : WordsTestChoose(questions[currentPos], nextClick: nextClick)),
          Container(
              padding: EdgeInsets.all(6),
              child: LinearProgressIndicator(value: progress, color: MyColor.Orange, backgroundColor: Color(0xffffeade)))
        ]),
        bgColor: MyColor.F8,
        resizeToAvoidBottomInset: false);
  }
}

///圖片填空題
class WordsTestImage extends StatefulWidget {
  dynamic question;
  Function(int state) nextClick;
  String questionContent = "";
  String questionImg = "";
  String answer = "";
  int state = WordsTest.NoAnswer;

  WordsTestImage(this.question, {required this.nextClick}) {
    state = WordsTest.NoAnswer;
    for (var item in question["answers"]) {
      if (item["isAnswer"]) {
        answer = item["answerContent"];
      }
    }
    questionContent = question["questionContent"];
    questionImg = question["questionImg"] ?? "";
    print("WordsTestImage:refresh");
  }

  @override
  State<StatefulWidget> createState() {
    return _WordsTestImage();
  }
}

class _WordsTestImage extends State<WordsTestImage> {
  TextEditingController controller = TextEditingController();

  answerClick() {
    String userAnswer = controller.text;
    bool isRight = userAnswer == widget.answer;
    HttpGo(context).post("/HiNote/AnswerVocabularyQuiz", {
      "vocabularyQuizId": WordsTest.vocabularyQuizId,
      "vocabularyId": widget.question["questionId"],
      "answer": userAnswer,
      "answerTotalSecond": WordsTest.sec,
      "isRight": isRight
    }, (data) {
      widget.state = isRight ? WordsTest.AnswerRight : WordsTest.AnswerError;
      controller.clear();
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    String yes = "恭喜答對了！";
    String errorTip = "正確答案：${widget.answer}";
    return Container(
        child: Column(children: [
      Container(
          height: 160,
          child: widget.state == WordsTest.NoAnswer
              ? Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                  Row(mainAxisSize: MainAxisSize.min, children: [
                    Container(width: 150, height: 32, child: NormalInput(inputType: NormalInput.Email, controller: controller)),
                    LocalImage("right-circle.png", width: 32, onTap: answerClick),
                  ]),
                  Container(height: 1, color: MyColor.C9, width: 150, margin: EdgeInsets.only(right: 48))
                ])
              : Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                  Text(widget.state == WordsTest.AnswerRight ? yes : errorTip,
                      style: TextStyle(
                          fontSize: 16,
                          color: widget.state == WordsTest.AnswerRight ? Color(0xff7fca52) : MyColor.Red,
                          fontWeight: FontWeight.bold)),
                  Button("Next",
                      isBorderBg: true,
                      bgColor: widget.state == WordsTest.AnswerRight ? Color(0xff7fca52) : MyColor.Red,
                      height: 24,
                      radius: 12,
                      width: 100,
                      margin: EdgeInsets.all(8), onTap: () {
                    widget.nextClick(widget.state);
                  })
                ])),
      Expanded(
          child: Container(
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(color: Color(0xfffffffff), borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
              width: double.infinity,
              child: Column(children: [
                Visibility(
                  child: Expanded(child: NetImage(widget.questionImg)),
                  visible: widget.questionImg.isNotEmpty,
                ),
                WordsPlayer(words: widget.questionContent, margin: EdgeInsets.only(bottom: 12)),
              ])))
    ]));
  }
}

/// 選擇題
class WordsTestChoose extends StatefulWidget {
  dynamic question;
  Function(int sate) nextClick;

  int state = WordsTest.NoAnswer;
  List<String> answerChooses = [];
  String questionContent = "";
  String answer = "";

  WordsTestChoose(this.question, {required this.nextClick}) {
    state = WordsTest.NoAnswer;
    for (var item in question["answers"]) {
      answerChooses.add(item["answerContent"]);
      if (item["isAnswer"]) {
        answer = item["answerContent"];
      }
    }
    questionContent = question["questionContent"];
  }

  @override
  State<StatefulWidget> createState() {
    return _WordsTestChoose();
  }
}

class _WordsTestChoose extends State<WordsTestChoose> {
  int chooseIndex = -1;

  answerClick() {
    if (chooseIndex < 0) {
      return;
    }
    String userAnswer = widget.answerChooses[chooseIndex];
    bool isRight = userAnswer == widget.answer;
    HttpGo(context).post("/HiNote/AnswerVocabularyQuiz", {
      "vocabularyQuizId": WordsTest.vocabularyQuizId,
      "vocabularyId": widget.question["questionId"],
      "answer": userAnswer,
      "answerTotalSecond": WordsTest.sec,
      "isRight": isRight
    }, (data) {
      widget.state = isRight ? WordsTest.AnswerRight : WordsTest.AnswerError;
      chooseIndex = -1;
      setState(() {});
    }, (code, error) => showToast(error));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    String yes = "恭喜答對了！";
    String errorTip = "正確答案：${widget.answer}";
    return Container(
        padding: EdgeInsets.fromLTRB(12, 32, 12, 12),
        child: Column(children: [
          Expanded(
              child: Container(
                  child: Column(children: [
            Text(widget.questionContent, style: TextStyle(fontSize: 20, color: MyColor.C7D, fontWeight: FontWeight.bold)),
            ListView.builder(
                itemCount: widget.answerChooses.length,
                shrinkWrap: true,
                padding: EdgeInsets.fromLTRB(0, 16, 0, 32),
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  return ItemChoose(widget.answerChooses[index],
                      isRightChoose: widget.answerChooses[index] == widget.answer,
                      isChoose: chooseIndex == index,
                      showAnswer: widget.state != WordsTest.NoAnswer, onChoose: () {
                    if (widget.state != WordsTest.NoAnswer) {
                      return;
                    }
                    chooseIndex = index;
                    setState(() {});
                  });
                }),
            Visibility(visible: widget.state == WordsTest.NoAnswer, child: LocalImage("right-circle.png", width: 36, onTap: answerClick)),
            Visibility(
                visible: widget.state != WordsTest.NoAnswer,
                child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                  Text(widget.state == WordsTest.AnswerRight ? yes : errorTip,
                      style: TextStyle(
                          fontSize: 16,
                          color: widget.state == WordsTest.AnswerRight ? Color(0xff7fca52) : MyColor.Red,
                          fontWeight: FontWeight.bold)),
                  Button("Next",
                      isBorderBg: true,
                      bgColor: widget.state == WordsTest.AnswerRight ? Color(0xff7fca52) : MyColor.Red,
                      height: 24,
                      radius: 12,
                      width: 100,
                      margin: EdgeInsets.all(8), onTap: () {
                    widget.nextClick(widget.state);
                  })
                ]))
          ]))),
        ]));
  }
}

class ItemChoose extends StatelessWidget {
  bool showAnswer = false;
  bool isChoose = false;
  bool isRightChoose = false;
  String text;
  Function()? onChoose;

  ItemChoose(this.text, {required this.isChoose, required this.isRightChoose, required this.showAnswer, this.onChoose});

  @override
  Widget build(BuildContext context) {
    Color bgColor = isChoose ? Color(0xffffeade) : MyColor.White;
    Color fontColor = isChoose ? MyColor.Orange : MyColor.C7D;
    if (showAnswer && isRightChoose) {
      bgColor = Color(0xff7fca52);
      fontColor = MyColor.White;
    }
    return GestureDetector(
        onTap: onChoose,
        child: Container(
            width: double.infinity,
            height: 40,
            margin: EdgeInsets.all(6),
            alignment: Alignment.center,
            decoration: Global.getBg_shadow(6, MyColor.DD, bgColor),
            child: Text(text, style: TextStyle(fontSize: 14, color: fontColor, fontWeight: FontWeight.bold))));
  }
}
